<template>
  <div class="box">
    <el-form
      ref="ruleFormRef"
      :model="form"
      label-position="right"
      label-width="120px"
      :inline="false"
      :rules="rules"
    >
      <el-form-item label="计划内容：" required prop="planContent">
        <el-input
          disabled
          maxlength="512"
          show-word-limit
          type="textarea"
          :rows="5"
          v-model="form.planContent"
        />
      </el-form-item>
      <el-form-item label="执行情况：" required prop="implementationStatus">
        <el-input
          :disabled="currentHandle=='详情'"
          maxlength="512"
          show-word-limit
          type="textarea"
          :rows="5"
          v-model="form.implementationStatus"
        />
      </el-form-item>
      <el-form-item label="延迟完成内容及原因：" required prop="delayReasons">
        <el-input
        :disabled="currentHandle=='详情'"
          maxlength="512"
          show-word-limit
          type="textarea"
          :rows="5"
          v-model="form.delayReasons"
        />
      </el-form-item>
      <el-form-item label="下阶段工作重点及保证措施：" required prop="guaranteeMeasures">
        <el-input
        :disabled="currentHandle=='详情'"
          maxlength="512"
          show-word-limit
          type="textarea"
          :rows="5"
          v-model="form.guaranteeMeasures"
        />
      </el-form-item>
      <el-form-item label="其他说明：">
        <el-input
        :disabled="currentHandle=='详情'"
          maxlength="512"
          show-word-limit
          type="textarea"
          :rows="5"
          v-model="form.otherInstructions"
        />
      </el-form-item>
      <el-form-item label="授权专利：">
        <el-input disabled placeholder="请选择" v-model="awardList.authorizedPatent">
          <template #append>
            <el-button :disabled="currentHandle=='详情'" type="primary" @click="handleAwards(1)">选择</el-button>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item label="授权软著：">
        <!-- <el-input v-model="form.authorizedSoftworks" /> -->
        <el-input disabled placeholder="请选择" v-model="awardList.authorizedSoftworks">
          <template #append>
            <el-button :disabled="currentHandle=='详情'" type="primary" @click="handleAwards(2)">选择</el-button>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item label="学术著作：">
        <!-- <el-input v-model="form.schoolWorks" /> -->
        <el-input disabled placeholder="请选择" v-model="awardList.schoolWorks">
          <template #append>
            <el-button :disabled="currentHandle=='详情'" type="primary" @click="handleAwards(3)">选择</el-button>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item label="学术论文：">
        <!-- <el-input v-model="form.academicPapers" /> -->
        <el-input disabled placeholder="请选择" v-model="awardList.academicPapers">
          <template #append>
            <el-button :disabled="currentHandle=='详情'" type="primary" @click="handleAwards(4)">选择</el-button>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item label="科技奖项">
        <!-- <el-input v-model="form.technologyAwards" /> -->
        <el-input disabled placeholder="请选择" v-model="awardList.technologyAwards">
          <template #append>
            <el-button :disabled="currentHandle=='详情'" type="primary" @click="handleAwards(5)">选择</el-button>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item label="附件:">
        <el-upload
          v-model:file-list="attachmentFile"
          :disabled="currentHandle=='详情'"
          ref="uploadRef"
          :limit="3"
          :headers="headers"
          action="/fastDfs/file/upload"
          :on-success="handleAttachment"
          :on-preview="previewAttachment"
          :on-remove="removeAttachment"
          :on-exceed="handleExceed"
          :on-error="handleError"
        >
          <el-button type="primary">点击上传</el-button>
        </el-upload>
      </el-form-item>
      <el-dialog v-model="data.awardsDialog" width="50%" title="选择成果">
        <achievement
          ref="awardsRef"
          v-if="data.awardsDialog"
          :tableArr="data.tableArr"
          :columns="data.columns"
          :isCheckbox="true"
          :loading="data.loading"
        ></achievement>
        <template #footer>
          <el-button @click="data.awardsDialog = false">关闭</el-button>
          <el-button type="primary" @click="getAwards">确认</el-button>
        </template>
      </el-dialog>
    </el-form>
  </div>
</template>
<script lang="ts">
import { defineComponent, reactive, ref } from 'vue'
import { useStore } from 'vuex'
import { ElMessage } from 'element-plus'
import achievement from '@/views/project/project-manage/components/achievement.vue'
import {
  getProjectPatent,
  getProjectSoftware,
  getProjectAcademic,
  getProjectThesis,
  getProjectAwards,
} from '@/views/project/api/project'
import tableData from '@/views/project/project-manage/components/tableHeader.json'
import { type } from '@/utils/utils'

export default defineComponent({
  components: { achievement },
  props:{
    currentHandle:{
      type: String,
      default:''
    },
  },
  setup(props) {
    const store = useStore()
    const form = reactive(store.state.projectCenter.reportForm)
    const awardList = reactive({
      authorizedPatent: '',
      authorizedSoftworks: '',
      schoolWorks: '',
      academicPapers: '',
      technologyAwards: '',
    })
    const initAwardList = () => {
      console.log(
        type(form.newAuthorizedPatent),
        type(form.newAuthorizedSoftworks),
        type(form.newTechnologyAwards),
        'asdasdasd'
      )

      awardList.authorizedPatent = type(form.newAuthorizedPatent)
        ? JSON.parse(form.newAuthorizedPatent)
            .map((item) => {
              return item.patentName
            })
            .join(',')
        : ''
      awardList.authorizedSoftworks = type(form.newAuthorizedSoftworks)
        ? JSON.parse(form.newAuthorizedSoftworks)
            .map((item) => {
              return item.name
            })
            .join(',')
        : ''
      awardList.schoolWorks = type(form.newSchoolWorks)
        ? JSON.parse(form.newSchoolWorks)
            .map((item) => {
              return item.name
            })
            .join(',')
        : ''
      awardList.academicPapers = type(form.newAcademicPapers)
        ? JSON.parse(form.newAcademicPapers)
            .map((item) => {
              return item.title
            })
            .join(',')
        : ''
      awardList.technologyAwards = type(form.newTechnologyAwards)
        ? JSON.parse(form.newTechnologyAwards)
            .map((item) => {
              return item.awardName
            })
            .join(',')
        : ''
    }
    initAwardList()

    const rules = reactive({
      planContent: { required: true, message: '请填写计划内容' },
      implementationStatus: { required: true, message: '请填写执行情况：' },
      delayReasons: { required: true, message: '请填写延迟完成内容及原因：：' },
      guaranteeMeasures: { required: true, message: '请填写下阶段工作重点及保证措施：：' },
    })
    const data = reactive({
      awardsDialog: false,
      currentAwards: 0,
      tableArr: [],
      columns: '' as any,
      loading: false,
      params: {
        current: 1,
        size: 30,
        projectId: store.state.projectCenter.reportForm.projectId,
      },
      filePathArray: [] as any,
      fileNameArray: [] as any,
    })
    const awardsRef = ref()
    let attachmentFile = []
    if (form.filePath.length > 0) {
      attachmentFile = type(form.filePath)
        ? JSON.parse(form.fileName).map((item, index) => {
            return {
              name: item,
              url: JSON.parse(form.filePath)[index],
            }
          })
        : []
    }    
    console.log(attachmentFile, 'attachmentFile-repert')
    const handleAwards = (index: number) => {
      data.awardsDialog = true
      data.currentAwards = index
      data.loading = true
      if (data.currentAwards == 1) {
        data.columns = tableData.patentHeader
        getProjectPatent(data.params).then((res) => {
          if (res.data.code == 200) {
            let result = res.data.data
            data.tableArr = result.records
            data.loading = false
          }
        })
      } else if (data.currentAwards == 2) {
        data.columns = tableData.softwareHeader
        getProjectSoftware(data.params).then((res) => {
          if (res.data.code == 200) {
            let result = res.data.data
            data.tableArr = result.records
            data.loading = false
          }
        })
      } else if (data.currentAwards == 3) {
        data.columns = tableData.compositionHeader
        getProjectAcademic(data.params).then((res) => {
          if (res.data.code == 200) {
            let result = res.data.data
            data.tableArr = result.records
            data.loading = false
          }
        })
      } else if (data.currentAwards == 4) {
        data.columns = tableData.thesisHeader
        getProjectThesis(data.params).then((res) => {
          if (res.data.code == 200) {
            let result = res.data.data
            data.tableArr = result.records
            data.loading = false
          }
        })
      } else if (data.currentAwards == 5) {
        data.columns = tableData.technologyawardsHeader
        getProjectAwards(data.params).then((res) => {
          if (res.data.code == 200) {
            let result = res.data.data
            data.tableArr = result.records
            data.loading = false
          }
        })
      }
    }
    const getAwards = () => {
      let awardsList = awardsRef.value.hasChoose()
      if (awardsList.length >= 1) {
        data.awardsDialog = false
        console.log(awardsList, 'awardsList')
        if (data.currentAwards == 1) {
          form.newAuthorizedPatent = JSON.stringify(
            awardsList.map((item) => {
              return {
                patentName: item.patentName,
                id: item.id,
              }
            })
          )
        } else if (data.currentAwards == 2) {
          form.newAuthorizedSoftworks = JSON.stringify(
            awardsList.map((item) => {
              return {
                name: item.name,
                id: item.id,
              }
            })
          )
        } else if (data.currentAwards == 3) {
          form.newSchoolWorks = JSON.stringify(
            awardsList.map((item) => {
              return {
                name: item.name,
                id: item.id,
              }
            })
          )
        } else if (data.currentAwards == 4) {
          form.newAcademicPapers = JSON.stringify(
            awardsList.map((item) => {
              return {
                title: item.title,
                id: item.id,
              }
            })
          )
        } else if (data.currentAwards == 5) {
          form.newTechnologyAwards = JSON.stringify(
            awardsList.map((item) => {
              return {
                awardName: item.awardName,
                id: item.id,
              }
            })
          )
        }
        initAwardList()
      } else {
        ElMessage({
          message: '请选择一项成果',
          type: 'warning',
        })
      }
    }
    const handleAttachment = (uploadFile) => {
      if (uploadFile.code == 200) {
        ElMessage({
          message: '上传成功',
          type: 'success',
        })
        data.filePathArray.push(uploadFile.data.path)
        data.fileNameArray.push(uploadFile.data.fileName)
      } else {
        ElMessage({
          message: '上传失败',
          type: 'error',
        })
      }
    }
    const previewAttachment = (uploadFile) => {
      console.log(uploadFile,'previewAttachment');
      if (props.currentHandle?.includes('详情')) {
        window.open(uploadFile.url)
      } else {
        window.open(uploadFile.response.data.path)
      }
      // window.open(uploadFile.response.data.path)
    }
    const removeAttachment = (file, uploadFiles) => {
      console.log(uploadFiles, 'uploadFiles')
      data.filePathArray = uploadFiles.map((fileItem) => {
        return fileItem.response.data.path
      })
      data.fileNameArray = uploadFiles.map((fileItem) => {
        return fileItem.response.data.fileName
      })
    }
    const handleExceed = () => {
      ElMessage({
        message: '最多上传3个附件',
        type: 'wraning',
      })
    }
    const handleError = () => {
      ElMessage({
        message: '上传失败',
        type: 'error',
      })
    }
    const ruleFormRef = ref()
    const submitForm = async () => {
      form.filePath = JSON.stringify(data.filePathArray)
      form.fileName = JSON.stringify(data.fileNameArray)
      return new Promise((resolve, reject) => {
        ruleFormRef.value.validate((valid) => {
          console.log(valid, 'valid')
          if (valid) {
            resolve(form)
          } else {
            ElMessage({
              message: '请将基本信息补充完整',
              type: 'warning',
            })
            reject('校验失败')
          }
        })
      })
    }
    const cookie = () => localStorage.getItem('token')
    return {
      store,
      form,
      data,
      awardList,
      rules,
      attachmentFile,
      awardsRef,
      ruleFormRef,
      initAwardList,
      handleAwards,
      getAwards,
      submitForm,
      handleAttachment,
      previewAttachment,
      removeAttachment,
      handleExceed,
      handleError,
      headers: {
        Authorization: 'Bearer ' + cookie(),
      },
    }
  },
  beforeUnmount() {
    console.log('进度上报组件卸载了')
    for (let key in this.form) {
      this.form[key] = ''
    }
  },
})
</script>
<style lang="scss" scoped>
.box {
  max-height: 500px;
  overflow: auto;
}
:deep(.el-upload-list__item.is-success.focusing .el-icon-close-tip) {
  display: none !important;
}
.el-form-item {
  width: 95%;
  margin: 10px auto;
}
</style>
